import React, { useState, useEffect, useRef } from 'react';
import { Box, List, ListItem, ListItemAvatar, ListItemText, Avatar, Typography, Divider, Badge, IconButton, TextField } from '@mui/material';
import { MoreVert as MoreVertIcon, Search as SearchIcon } from '@mui/icons-material';
import { VariableSizeList } from 'react-window';
import { GetFriendList } from '../services/addressBookService';
import { dbService } from '../services/dbService';

const AddressBook = ({ onSelectFriend, setShowAddressBook }) => {
  const [friends, setFriends] = useState([]);
  const [searchText, setSearchText] = useState('');
  const [loading, setLoading] = useState(true);
  const listRef = useRef();
  
  // 加载通讯录数据
  useEffect(() => {
    const loadAddressBook = async () => {
      try {
        setLoading(true);
        // 先从IndexedDB中获取通讯录数据
        const addressBookData = await dbService.get(dbService.getStoreNames().ADRESSBOOK, 'addressbook');
        
        if (addressBookData && addressBookData.data && addressBookData.data.length > 0) {
          // 如果IndexedDB中有数据，直接使用
          console.log('从IndexedDB加载通讯录数据成功');
          // 确保数据按拼音首字母排序
          const sortedFriends = [...addressBookData.data].sort((a, b) => {
            const pyA = a.remark?.toLowerCase() ||a.name?.toLowerCase() || '';
            const pyB = b.remark?.toLowerCase() ||b.name?.toLowerCase() || '';;
            return pyA.localeCompare(pyB);
          });
          setFriends(sortedFriends);
        } else {
          // 如果没有数据，则调用API获取
          console.log('IndexedDB中没有通讯录数据，从API获取');
          const friendList = await GetFriendList();
          
          if (friendList && friendList.length > 0) {
            // 处理API返回的数据格式
            const processedFriends = friendList.map(friend => ({
              id: friend.userName?.str || '',
              name: friend.nickName?.str || friend.userName?.str || '',
              avatar: friend.smallHeadImgUrl?.trim() || '',
              alias: friend.alias || '',
              pyinitial: friend.pyinitial?.str || '',
              remark: friend.remark?.str || ''
            }));
            
            // 按拼音首字母排序
            processedFriends.sort((a, b) => {
              const pyA = a.pyinitial.toLowerCase();
              const pyB = b.pyinitial.toLowerCase();
              return pyA.localeCompare(pyB);
            });
            
            // 保存到IndexedDB
            await dbService.set(dbService.getStoreNames().ADRESSBOOK, {
              id: 'addressbook',
              data: processedFriends
            });
            
            setFriends(processedFriends);
            console.log('通讯录数据已保存到IndexedDB');
          }
        }
      } catch (error) {
        console.error('加载通讯录失败:', error);
      } finally {
        setLoading(false);
      }
    };
    
    loadAddressBook();
  }, []);
  
  // 处理搜索
  const handleSearch = (e) => {
    setSearchText(e.target.value);
  };
  
  // 过滤好友列表
  const filteredFriends = friends.filter(friend => {
    if (!searchText) return true;
    const searchLower = searchText.toLowerCase();
    return (
      friend.name.toLowerCase().includes(searchLower) ||
      friend.alias.toLowerCase().includes(searchLower) ||
      friend.remark.toLowerCase().includes(searchLower)||
      friend.pyinitial.toLowerCase().includes(searchLower)
    );
  });
  
  // 列表项高度
  const itemSize = 60;
  const getItemSize = () => itemSize;
  
  // 处理双击联系人事件
  const handleDoubleClick = (friend) => {
    // 如果提供了onSelectContact回调，则调用它并传递联系人ID
    if (onSelectFriend && friend.id) {
      // 切换到聊天界面
      onSelectFriend(friend);
      // 关闭通讯录视图
      if (setShowAddressBook) {
        setShowAddressBook(false);
      }
    }
  };

  // 列表项渲染
  const Row = ({ index, style, data }) => {
    const friend = data[index];
    
    return (
      <div style={style}>
        <ListItem 
          alignItems="flex-start"
          sx={{
            padding: '8px 12px',
            minHeight: '48px',
            cursor: 'pointer',
            '&:hover': {
              backgroundColor: '#e6e6e6'
            }
          }}
          onDoubleClick={() => handleDoubleClick(friend)}
        >
          <ListItemAvatar>
            <Avatar src={friend.avatar} alt={friend.name} />
          </ListItemAvatar>
          <ListItemText
            primary={
              <Typography component="span" variant="body1" sx={{ 
                fontSize: '0.875rem',
                whiteSpace: 'nowrap',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                maxWidth: '180px'
              }}>
                {friend.remark ||friend.name }
              </Typography>
            }
            secondary={
              friend.alias ? (
                <Typography
                  component="span"
                  variant="body2"
                  color="text.secondary"
                  sx={{
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    display: '-webkit-box',
                    WebkitLineClamp: 1,
                    WebkitBoxOrient: 'vertical',
                    fontSize: '0.8125rem'
                  }}
                >
                  {friend.alias}
                </Typography>
              ) : null
            }
          />
        </ListItem>
      </div>
    );
  };
  
  return (
    <Box sx={{ height: '100%', width: '100%', bgcolor: '#f5f5f5' }}>
      <Box sx={{ 
        p: 1.2, 
        bgcolor: '#f5f5f5', 
        color: 'text.primary',
        display: 'flex', 
        alignItems: 'center',
        gap: 1
      }}>
        <TextField
          size="small"
          placeholder="搜索通讯录"
          value={searchText}
          onChange={handleSearch}
          sx={{ 
            flexGrow: 1,
            '& .MuiOutlinedInput-root': {
              borderRadius: 20,
              backgroundColor: '#fff',
              height: 30,
              padding: '6px 12px'
            }
          }}
        />
        <IconButton color="primary" size="small" sx={{ '& svg': { color: '#595959' } }}>
          <SearchIcon />
        </IconButton>
      </Box>
      
      <Box sx={{ flex: 1 }}>
        {loading ? (
          <Box sx={{ display: 'flex', justifyContent: 'center', p: 3 }}>
            <Typography>加载通讯录中...</Typography>
          </Box>
        ) : filteredFriends.length > 0 ? (
          <VariableSizeList
            height={window.innerHeight - 56}
            width="100%"
            itemCount={filteredFriends.length}
            itemSize={getItemSize}
            itemData={filteredFriends}
            ref={listRef}
          >
            {Row}
          </VariableSizeList>
        ) : (
          <Box sx={{ display: 'flex', justifyContent: 'center', p: 3 }}>
            <Typography>没有找到联系人</Typography>
          </Box>
        )}
      </Box>
    </Box>
  );
};

export default AddressBook;